<template>
<div>
    <el-col :span="24">
        <div style="align-items: center;display: flex;">
        <el-input @click.native="openF7" v-model="myloadShow" suffix-icon="el-icon-s-grid" :disabled="f7Disable" :placeholder="placeholder"></el-input>
        <i style="margin-left: 5px;" class="el-icon-delete-solid"  @click.prevent="cleanF7"/> 
        </div>
    </el-col>
        <el-dialog class="vxe-table--ignore-clear" center :title="title" :visible.sync="isShowVisible" :close-on-click-modal="true" width="70%" top="3vh" append-to-body>
            <div class="el-dialog-div">
                <el-container>
                    <el-aside :width = "sideWidth">
                        <el-card class="box-card">
                            <el-input style="margin-bottom: 5px" placeholder="输入关键字进行过滤"  v-model="filterText"></el-input>
                            <el-tree
                                style="height:60vh;overflow:auto;" 
                                class="filter-tree"
                                :data="groupTreeData"
                                :props="defaultProps"
                                default-expand-all
                                @node-click="handleNodeClick"
                                highlight-current
                                :expand-on-click-node="false"
                                :filter-node-method="filterNode"
                                :render-content="renderContent"
                                v-loading="treeLoading"
                                ref="groupTree">
                            </el-tree>
                        </el-card>
                    </el-aside>
                    <el-main style="padding: 0px !important;">
                        <el-card style="height: 100%;">
                            <!-- <el-row :gutter="20" style="margin-bottom: 20px;" > -->
                                <template>
                                    <el-row v-for="(page, index) of inputPages" :key="index" style="margin-bottom: 20px;">
                                        <el-col :span="4" v-for="(item, innerindex) of page" :key="item.projectId" :offset="innerindex > 0 ? 1 : 0"> <el-input type="text" :placeholder="item.lable" v-model="item.model" @input="change($event)"></el-input> </el-col>
                                        <el-col :span="4" :offset="filterQuery.length%5==0?0:1" :style="filterQuery.length%5==0?('margin-top:20px'):''">
                                            <el-button-group v-if="index===inputPages.length-1">
                                                <el-button type="primary" icon="el-icon-search" @click="searchData"></el-button>
                                                <el-button type="success" icon="el-icon-refresh" @click="clearData"></el-button>
                                            </el-button-group>
                                        </el-col>
                                    </el-row>
                                </template>
                            <el-table border :data="dataList" v-loading="tableLoading"  ref='iTable1' :height="50+'vh'" @row-click="handleRowClick" @row-dblclick="handleRowDbClick">
                                <el-table-column v-if="isMultiSelect" align="center" type="selection" width="55"></el-table-column>
                                <template v-for="(item,index) in f7Param.column">
                                    <el-table-column :label="item.lable" :key="item.prop" :prop="item.prop" min-width='100' >
                                    </el-table-column>
                                </template>
                            </el-table>
                            <el-pagination
                                style="float:right; margin: 10px 0;"
                                @size-change="handleSizeChange"
                                @current-change="handleCurrentChange"
                                :current-page="page"
                                :page-sizes="[10, 15, 20, 50]"
                                :page-size="pageSize"
                                layout="total, sizes, prev, pager, next, jumper"
                                prev-text="上一页"
                                next-text="下一页"
                                :total="totalRows">
                            </el-pagination>
                        </el-card>
                    </el-main>
                </el-container>
            </div>
            <div v-if="isMultiSelect" slot="footer" class="dialog-footer">
                        <el-button type="primary" @click="multiData">确定</el-button>
                        <el-button @click="multiCancel">取消</el-button>
            </div>
        </el-dialog>      
</div>
</template>
<script>
    import HttpHandler from "@/handler/HttpHandler";
    export default {
        name: "common-f7",
        props: {
            f7Param: {type:Object},
            /**
             * selectId为具体存值；必填
             * selectUrl为查询分页数据的URL地址；必填
             * selectTreeField为过滤树的字段名；选填
             * selectTreeUrl为查询树结构的URL地址；选填
             * selectShow表示展示样式，spt为分隔符，field表示需要展示列，如spt为“-”，filed为name和number，即展示为“name值-number值”
             * column表示table展示列，lable为展示列列头，prop表示展示列属性，isFilter表示此列是否参与过滤，filterField表示参与过滤列名
             */
            loadShow:[String],
            f7Disable:false,
            /**
             * f7是否可用
             */
            title:{type:String},
            /** 
             * F7标题
            */
            isMultiSelect:false,
            /** 
             * true为多选，false为单选
            */
           placeholder : '',
        },
        data(){
            return {
                myloadShow:'',
                filterQuery:[],
                selectTreeField:[],
                selectTreeHttp:{},
                selectHttp:{},
                sideWidth:'0px',
                fgroupId:{},
                isShowVisible:false,
                filterText:'',
                groupTreeData:[],
                dataList:[],
                defaultProps:{children: 'children',label: 'nodeName'},
                page: 1, 
                pageSize: 10, 
                totalRows: 0, 
                treeLoading:'',
                tableLoading:'',
                apiTableCount:0,
                apiTreeCount:0
            }
        },
        created(){
            this.myloadShow = this.loadShow
            this.selectHttp=new HttpHandler()
            this.selectTreeHttp = new HttpHandler()
            for (let i = 0; i < this.f7Param.column.length; i++) {
                if(this.f7Param.column[i].isFilter){
                    let filter = {}
                    filter["lable"]=this.f7Param.column[i].lable
                    filter["prop"]=this.f7Param.column[i].prop
                    filter["filterField"]=this.f7Param.column[i].filterField
                    filter["model"]=''
                    this.filterQuery.push(filter)
                }
            }
            this.getTreeData()
            this.getTableData()
        },
        computed: {
            inputPages () {
                const inputPages = []
                this.filterQuery.forEach((item, index) => {
                    const page = Math.floor(index / 5)
                    if (!inputPages[page]) {
                        inputPages[page] = []
                    }
                    inputPages[page].push(item)
                })
                return inputPages
            }
        },
        watch: {
            filterText(val) {
                this.$refs.groupTree.filter(val);
            },
            apiTreeCount(val){
                if(val>0){
                    this.treeLoading=true
                }else{
                    this.treeLoading=false
                }
            },
            apiTableCount(val){
                if(val>0){
                    this.tableLoading=true
                }else{
                    this.tableLoading=false
                }
            }
        },
        methods:{
            change(e){
                this.$forceUpdate()
            },
            //多选确定按钮
            multiData(){
                const _selectData = this.$refs.iTable1.selection;
                if(_selectData.length==0){
                    this.$tie.showError('请至少选择一条数据！')
                    return
                }
                let fids = '';
                let fnames = '';
                for(var i = 0 ; i < _selectData.length ;i++){
                    fids = fids+','+_selectData[i][this.f7Param.selectId]
                    let myspt = this.f7Param.selectShow.spt
                    let myshow = ''
                    if(_.isEmpty(this.f7Param.selectShow.spt)){
                        myspt = ''
                    }
                    for (var j = 0; j < this.f7Param.selectShow.field.length; j++) {
                        if(j==0){
                             myshow += _selectData[i][this.f7Param.selectShow.field[j]]
                        }else{
                            myshow += myspt+_selectData[i][this.f7Param.selectShow.field[j]]
                        }
                    }
                    fnames = fnames+','+myshow
                }
                fnames=fnames.substr(1,fnames.length);
                fids=fids.substr(1,fids.length)
                this.myloadShow = fnames
                this.$emit('input',fids)
                this.$emit('onF7DaTaSelected',_selectData)
                this.isShowVisible = false
            },
            multiCancel(){
                this.isShowVisible = false
                this.refresh();
            },
            //手动刷新
            refresh(){
                this.fgroupId.fid = null
                this.fgroupId.field = null
                this.pageSize=10
                this.page=1
                this.getTreeData()
                
                this.getTableData()
            },
            //默认携带函数
            defaultSelect(data){
                if(this.f7Param.selectShow.field.length==1){
                        this.myloadShow = data[this.f7Param.selectShow.field[0]]
                    }else{
                        let myspt = this.f7Param.selectShow.spt
                        let myshow = ''
                        if(_.isEmpty(this.f7Param.selectShow.spt)){
                            myspt = ''
                        }
                        for (var i = 0; i < this.f7Param.selectShow.field.length; i++) {
                            if(i==0){
                                myshow += data[this.f7Param.selectShow.field[i]]
                            }else{
                                myshow += myspt+data[this.f7Param.selectShow.field[i]]
                            }
                        }
                        this.myloadShow = myshow
                    }
                this.$emit('input',data[this.f7Param.selectId])
                if(data.isChange&&data.isChange=="0"){//参数字符串0和1，0代表不更新，1代表更新
                    
                }else{
                    this.$emit('onF7DaTaSelected',data)
                }
            },
            //打开F7选择弹窗
            openF7(){
                if(this.f7Disable){
                    return
                }else{
                    this.isShowVisible = true
                }
            },
            //清空F7：参数字符串0和1，0代表不更新，1代表更新
            cleanF7(isChange){
                if(this.f7Disable){
                    return
                }else{
                    this.myloadShow = null
                    this.$emit('input',null)
                    if(isChange&&isChange=="0"){
                        
                    }else{
                        this.$emit('onF7DaTaSelected',null)
                    }
                }
            },
            //关闭F7选择弹窗
            closeUserF7(){
                this.isShowVisible=false
            },
            //动态渲染树形图添加图片
            renderContent (h, { node, data, store }) {
                return (
                <span  class="el-tree-node__label">
                <i class={data.icon}></i>
                <span> {node.label}</span>
                </span>
                )
            },
            //F7选择弹窗获取树数据
            async getTreeData(){
                this.apiTreeCount++
                if(this.f7Param.selectTreeUrl&&this.f7Param.selectTreeUrl!=""&&this.f7Param.selectTreeField.length>0){
                    this.selectTreeField=this.f7Param.selectTreeField
                    this.sideWidth = ''
                    let data={}
                    if(this.f7Param.defaultTreeFilter){
                        for(var i = 0 ; i < this.f7Param.defaultTreeFilter.length ;i++){
                            if(this.f7Param.defaultTreeFilter[i]&&this.f7Param.defaultTreeFilter[i].value){
                                data[this.f7Param.defaultTreeFilter[i].field]=this.f7Param.defaultTreeFilter[i].value
                            }
                        }
                    }
                     let res = await this.selectTreeHttp.get(this.f7Param.selectTreeUrl,data)
                     let treeData = res.data
                     this.groupTreeData = this.allTurnTree(treeData, 'nodeId', 'nodePid', -2);
                }
                this.apiTreeCount--
            },
            //树结构修改
            allTurnTree(list, id="nodeId", parentId="nodePid"){
                let temp = {}
                let ans = []
                for (let i in list) {
                    temp[list[i][id]] = list[i]
                }
                for (let i in temp) {
                    if(this.selectTreeField.length>1){
                        for(let j in this.selectTreeField){
                            if(temp[temp[i][parentId]]&&i.indexOf(this.selectTreeField[j])==0){
                                if(!temp[temp[i][parentId]].children){
                                    temp[temp[i][parentId]].children = new Array()
                                }
                                temp[temp[i][parentId]].children.push(temp[i])
                            }
                        }
                    }else{
                        if (temp[i][parentId] !== -2 && temp[i][id]) {//&&temp[i][parentId] !== -2
                            if (!temp[temp[i][parentId]].children) {
                                temp[temp[i][parentId]].children = new Array()
                            }
                            temp[temp[i][parentId]].children.push(temp[i])
                        } else {
                            ans.push(temp[i])
                        }
                    }
                    
                    if(i.indexOf("-1")>0){
                        ans.push(temp[i])
                    }
                }
                if(ans.length !== 0 && !_.isArray(ans[0].children)){
                ans[0].children = []
                }
                return ans
            },
            //F7选择弹窗获取表格数据源
            async getTableData(){ 
                this.apiTableCount++
                let data={}
                for(var i = 0 ; i < this.filterQuery.length ;i++){
                    data[this.filterQuery[i].filterField]=this.filterQuery[i].model
                }
                if(this.f7Param.defaultFilter){
                    for(var i = 0 ; i < this.f7Param.defaultFilter.length ;i++){
                        if(this.f7Param.defaultFilter[i]&&this.f7Param.defaultFilter[i].value!=undefined){
                            data[this.f7Param.defaultFilter[i].field]=this.f7Param.defaultFilter[i].value
                        }
                    }
                }
                if(this.f7Param.selectTreeUrl&&this.f7Param.selectTreeUrl!=""&&this.f7Param.selectTreeField.length>0){
                    if(this.fgroupId.field!=undefined&&this.fgroupId.field!=null)
                        data[this.fgroupId.field]=this.fgroupId.fid
                }
                data["pageSize"]=this.pageSize
                data["page"]=this.page
                let res = await this.selectHttp.get(this.f7Param.selectUrl,data)
                this.dataList = res.data.rows
                this.page = res.data.page
                this.pageSize = res.data.pageSize
                this.totalRows = res.data.totalRows
                this.apiTableCount--
            },
            handleRowClick(row,column,event){
                if(this.isMultiSelect){
                    this.$refs.iTable1.toggleRowSelection(row)
                }
            },
            //F7选择弹窗双击
            handleRowDbClick(row,column,event){
                if(!this.isMultiSelect){
                    if(this.f7Param.selectShow.field.length==1){
                        let selectShow = this.f7Param.selectShow.field[0].split('.');
                        if(selectShow.length>1){
                            let select = row;
                            selectShow.forEach(function(element) {
                                select = select[element];
                            });
                            this.myloadShow = select;
                        }else{
                            this.myloadShow = row[selectShow[0]];
                        }
                    }else{
                        let myspt = this.f7Param.selectShow.spt
                        let myshow = ''
                        if(_.isEmpty(this.f7Param.selectShow.spt)){
                            myspt = ''
                        }
                        for (var i = 0; i < this.f7Param.selectShow.field.length; i++) {
                            if(i==0){
                                myshow += row[this.f7Param.selectShow.field[i]]
                            }else{
                                myshow += myspt+row[this.f7Param.selectShow.field[i]]
                            }
                        }
                        this.myloadShow = myshow
                    }
                    
                    let selectId = this.f7Param.selectId.split('.');
                    if(selectId.length>1){
                        let select = row;
                        selectId.forEach(function(element) {
                            select = select[element];
                        });
                        this.$emit('input',select)
                    }else{
                        this.$emit('input',row[this.f7Param.selectId])
                    }
                    this.$emit('onF7DaTaSelected',row)
                    this.isShowVisible = false
                }
            },
            //树结构筛选
            filterNode(value, data) {
                if (!value) return true;
                    return data.nodeName.indexOf(value) !== -1;
            },
            //树结构单击
            handleNodeClick(val){
                if((val.nodeId+"").indexOf("-1")<0){
                    if(this.selectTreeField.length>1){
                        for(let i in this.selectTreeField){
                            if(val.nodeId.indexOf(this.selectTreeField[i])==0){
                                this.fgroupId.fid=val.nodeId.substring(this.selectTreeField[i].length,val.nodeId.length)
                                this.fgroupId.field=this.selectTreeField[i]
                            }
                        }
                    }else{
                        this.fgroupId.fid=val.nodeId
                        this.fgroupId.field=this.selectTreeField[0]
                    }
                }else{
                    this.fgroupId.field=null
                }
                this.getTableData()
            },
            //当前页码修改时
            handleCurrentChange(page){
                this.page = page
                this.getTableData()
            },
            //当前页数修改时
            handleSizeChange(pageSize){
                this.pageSize = pageSize
                this.getTableData()
            },
            //查询列表
            searchData:function(){
                this.page = 1
                this.getTableData()
            },
            //清空搜索并刷新列表
            clearData(){
                for(var i = 0 ; i < this.filterQuery.length ;i++){
                    this.filterQuery[i].model=""
                }
                this.page = 1
                this.getTableData()
            },
        }
    }
</script>

<style >

</style>